package com.party.admin.biz.payquery;

import com.google.common.collect.Lists;
import com.party.admin.biz.activity.MemberActBizService;
import com.party.admin.biz.copartner.MemberCopartnerDetailBizService;
import com.party.admin.biz.crowdfund.SupportBizService;
import com.party.admin.biz.mall.MallOrderBizService;
import com.party.admin.biz.merchantAnalyze.MemberMerchantDetailBizService;
import com.party.admin.biz.order.OrderBizService;
import com.party.admin.biz.order.OrderTradeBizService;
import com.party.core.utils.MyBeanUtils;
import com.party.common.constant.Constant;
import com.party.common.utils.BigDecimalUtils;
import com.party.common.utils.DateUtils;
import com.party.common.utils.StringUtils;
import com.party.core.exception.OrderException;
import com.party.core.model.activity.ActStatus;
import com.party.core.model.activity.Activity;
import com.party.core.model.charge.PackageMember;
import com.party.core.model.crowdfund.Project;
import com.party.core.model.crowdfund.Support;
import com.party.core.model.crowdfund.TargetProject;
import com.party.core.model.member.MemberAct;
import com.party.core.model.order.*;
import com.party.core.model.wechat.WechatMerchants;
import com.party.core.model.wechatPlatform.WechatOpenMember;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.charge.IPackageMemberService;
import com.party.core.service.counterfoil.biz.CounterfoilBizService;
import com.party.core.service.crowdfund.*;
import com.party.core.service.distributor.IDistributorCountService;
import com.party.core.service.member.IMemberActService;
import com.party.core.service.member.IPartnerMemberService;
import com.party.core.service.order.IOrderFormInfoService;
import com.party.core.service.order.IOrderFormService;
import com.party.core.service.order.IOrderTradeService;
import com.party.core.service.wechat.IWechatMerchantsService;
import com.party.core.service.wechatPlatform.IWechatOpenMemberService;
import com.party.pay.model.pay.ali.PayResponse;
import com.party.pay.model.pay.wechat.NotifyRequest;
import com.party.pay.model.query.AliPayQueryResponse;
import com.party.pay.model.query.TradeStatus;
import com.party.pay.model.query.WechatPayQueryResponse;
import com.party.pay.model.refund.AliPayRefundInput;
import com.party.pay.model.refund.WechatPayRefundInput;
import com.party.pay.service.pay.PayOrderBizService;
import com.party.pay.service.query.QueryAliBizService;
import com.party.pay.service.query.QueryWechatBizService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

/**
 * 订单查询校正
 * Created by wei.li
 *
 * @date 2017/3/31 0031
 * @time 19:57
 */
@Service
public class OrderQueryBizService {
    /********************** 支付宝 ***********************/
    // 应用id
    @Value("#{refund_ali['alipay.appid']}")
    private String appId;

    // 应用私钥
    @Value("#{refund_ali['alipay.privatekey']}")
    private String privateKey;

    // 支付宝公钥
    @Value("#{refund_ali['alipay.publickey']}")
    private String publickey;

    // 签名方式
    @Value("#{refund_ali['alipay.sign_type']}")
    private String signType;
    /********************** 支付宝 ***********************/

    /********************** 微信 ***********************/
    /********************* APP *************************/
    @Value("#{pay_wechat_app['wechat.app.appId']}")
    private String app_appId;

    // 微信商户平台商户号
    @Value("#{pay_wechat_app['wechat.app.mchId']}")
    private String app_mchId;

    // 微信签名令牌
    @Value("#{pay_wechat_app['wechat.app.apiKey']}")
    private String app_apiKey;
    /********************* APP *************************/

    /********************* 微网站 *************************/
    /********************* 微网站 *************************/

    /********************* 小程序 *************************/
    // 小程序编号
    @Value("#{pay_wechat_xcx['wechat.xcx.appId']}")
    private String xcx_appId;

    // 小程序商户号
    @Value("#{pay_wechat_xcx['wechat.xcx.mchId']}")
    private String xcx_mchId;

    // 微信接口密钥
    @Value("#{pay_wechat_xcx['wechat.xcx.apiKey']}")
    private String xcx_apiKey;
    /********************* 小程序 *************************/
    /********************** 微信 ***********************/

    @Autowired
    QueryAliBizService queryAliBizService;
    @Autowired
    QueryWechatBizService queryWechatBizService;
    @Autowired
    IOrderFormInfoService orderFormInfoService;
    @Autowired
    IOrderFormService orderFormService;
    @Autowired
    OrderBizService orderBizService;
    @Autowired
    PayOrderBizService payOrderBizService;
    @Autowired
    IOrderTradeService orderTradeService;
    @Autowired
    SupportBizService supportBizService;
    @Autowired
    IProjectService projectService;
    @Autowired
    ISupportService supportService;
    @Autowired
    IMemberActService memberActService;
    @Autowired
    ISupportRefundService supportRefundService;
    @Autowired
    IProjectRefundService projectRefundService;
    @Autowired
    private MemberActBizService memberActBizService;
    @Autowired
    private IPackageMemberService packageMemberService;
    @Autowired
    private OrderTradeBizService orderTradeBizService;
    @Autowired
    private MemberCopartnerDetailBizService memberCopartnerDetailBizService;
    @Autowired
    private MemberMerchantDetailBizService memberMerchantDetailBizService;
    @Autowired
    private IDistributorCountService distributorCountService;
    @Autowired
    private IPartnerMemberService partnerMemberService;
    @Autowired
    private ICrowdfundRankService crowdfundRankService;
    @Autowired
    private IActivityService activityService;
    @Autowired
    private ITargetProjectService targetProjectService;
    @Autowired
    private IWechatOpenMemberService wechatOpenMemberService;
    @Autowired
    private IWechatMerchantsService wechatMerchantsService;
    @Autowired
    private MallOrderBizService mallOrderBizService;
    @Autowired
    private CounterfoilBizService counterfoilBizService;

    private static final int SUPPORT_IS_PAY = 1;

    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 更新订单相关信息
     *
     * @param payment       金额
     * @param orderId       订单编号
     * @param transactionId 交易编号
     * @param tradeState    交易状态
     * @param mchId         商户号
     */
    public OrderForm orderCallback(Float payment, String orderId, String transactionId, String tradeState, String mchId) {
        OrderForm t = orderFormService.get(orderId);
        if (payment != null) {
            t.setPayment(payment);
        }
        t.setTransactionId(transactionId);
        t.setTradeState(tradeState);
        t.setMerchantId(mchId);
        orderFormService.update(t);

        if (OrderType.ORDER_ACTIVITY.getCode().equals(t.getType())
                || OrderType.ORDER_COURSE.getCode().equals(t.getType())) {
            MemberAct memberAct = memberActService.findByOrderId(orderId);
            if (memberAct != null && payment != null) {
                if (OrderStatus.ORDER_STATUS_HAVE_PAID.getCode().equals(t.getStatus())) {
                    memberAct.setCheckStatus(ActStatus.ACT_STATUS_PAID.getCode());
                } else if (OrderStatus.ORDER_STATUS_REFUND.getCode().equals(t.getStatus())) {
                    memberAct.setCheckStatus(ActStatus.ACT_STATUS_AUDIT_REJECT.getCode());
                } else if (OrderStatus.ORDER_STATUS_OTHER.getCode().equals(t.getStatus())) {
                    memberAct.setCheckStatus(ActStatus.ACT_STATUS_CANCEL.getCode());
                }
                memberAct.setPayment(payment);
                memberActService.update(memberAct);
            }
            counterfoilBizService.getActivityCounterfoils(memberAct.getActId());
        }
        return t;
    }

    /**
     * 交易状态NOTPAY，订单状态等于已支付或者已退款，更改为待支付
     *
     * @param orderId 订单编号
     */
    public void updateNotPay(String orderId) {
        OrderForm t = orderFormService.get(orderId);
        t.setStatus(OrderStatus.ORDER_STATUS_TO_BE_PAID.getCode());
        orderFormService.update(t);
        if (t.getType().equals(OrderType.ORDER_ACTIVITY.getCode())
                || OrderType.ORDER_COURSE.getCode().equals(t.getType())) { // 活动报名
            MemberAct memberAct = memberActService.findByOrderId(orderId);
            memberAct.setCheckStatus(ActStatus.ACT_STATUS_AUDIT_PASS.getCode());
            memberActService.update(memberAct);
        } else if (t.getType().equals(OrderType.ORDER_CROWD_FUND.getCode())) { // 众筹支持
            Support support = supportService.findByOrderId(orderId);
            support.setPayStatus(0);
            supportService.update(support);
        } else if (t.getType().equals(OrderType.ORDER_LEVEL.getCode()) || t.getType().equals(OrderType.ORDER__BUY_SYSTEM)) { // 套餐订单
            PackageMember packageMember = packageMemberService.findByOrderId(orderId);
            packageMember.setPayStatus(1);
            packageMember.setStatus(2);
            packageMemberService.update(packageMember);
        }
    }

    /**
     * 微信订单查询校正
     *
     * @param queryResponse 查询响应参数
     * @param orderForm     订单信息
     * @throws Exception 异常信息
     */
    public void wxCallback(WechatPayQueryResponse queryResponse,
                           OrderForm orderForm, List<OrderForm> orderForms) throws Exception {
        // 更新金额
        Float payment = null;
        if (StringUtils.isNotEmpty(queryResponse.getTotalFee())) {
            int totalFee = Integer.valueOf(queryResponse.getTotalFee());
            double total = BigDecimalUtils.div(Double.valueOf(totalFee), Double.valueOf(100), 2);
            String value = String.valueOf(total);
            payment = Float.valueOf(value);
        }
        OrderForm t = this.orderCallback(payment, orderForm.getId(), queryResponse.getTransactionId(), queryResponse.getTradeState(), queryResponse.getMchId());

        if (queryResponse.getTradeState().equals(TradeStatus.WX_SUCCESS.getCode())
                && !orderForm.getStatus().equals(OrderStatus.ORDER_STATUS_HAVE_PAID.getCode())) {

            // 微信交易状态SUCCESS，订单状态不是已支付，手动回调
            NotifyRequest notifyRequest = new NotifyRequest();
            MyBeanUtils.copyBeanNotNull2Bean(queryResponse, notifyRequest);
            this.updatePayBusiness(orderForm, notifyRequest, PaymentWay.WECHAT_PAY.getCode());
            orderForms.add(t);
        } else if (queryResponse.getTradeState().equals(TradeStatus.WX_REFUND.getCode())
                && !orderForm.getStatus().equals(OrderStatus.ORDER_STATUS_REFUND.getCode())) {
            // 微信交易状态REFUND，订单状态不是已退款，手动回调
            this.updateRefund(orderForm, queryResponse);
            orderForms.add(t);
        } else if (queryResponse.getTradeState().equals(TradeStatus.WX_NOTPAY.getCode())) {
            // 微信交易状态NOTPAY，订单状态等于已支付或者已退款，更改为待支付
            if (orderForm.getStatus().equals(OrderStatus.ORDER_STATUS_HAVE_PAID.getCode())
                    || orderForm.getStatus().equals(OrderStatus.ORDER_STATUS_REFUND.getCode())) {
                this.updateNotPay(orderForm.getId());
                orderForms.add(t);
            }
        }
    }

    /**
     * 支付宝订单查询校正
     *
     * @param queryResponse 查询响应参数
     * @param orderForm     订单信息
     * @throws Exception 异常信息
     */
    public void aliCallback(AliPayQueryResponse queryResponse,
                            OrderForm orderForm, List<OrderForm> orderForms) throws Exception {
        // 更新金额
        Float payment = null;
        if (StringUtils.isNotEmpty(queryResponse.getTotalAmount())) {
            payment = Float.valueOf(queryResponse.getTotalAmount());
        }
        OrderForm t = this.orderCallback(payment, orderForm.getId(), queryResponse.getTradeNo(), queryResponse.getTradeStatus(), null);

        if (queryResponse.getTradeStatus().equals(TradeStatus.ALI_TRADE_SUCCESS.getCode())
                && !orderForm.getStatus().equals(OrderStatus.ORDER_STATUS_HAVE_PAID.getCode())) {

            // 支付宝交易状态TRADE_SUCCESS，订单状态不是已支付，手动回调
            PayResponse notifyRequest = new PayResponse();
            notifyRequest.setTotalFee(Float.valueOf(queryResponse.getTotalAmount()));
            MyBeanUtils.copyBeanNotNull2Bean(queryResponse, notifyRequest);
            this.updatePayBusiness(orderForm, notifyRequest, PaymentWay.ALI_PAY.getCode());
            orderForms.add(t);
        } else if (queryResponse.getTradeStatus().equals(TradeStatus.ALI_TRADE_CLOSED.getCode())
                && (orderForm.getStatus().equals(OrderStatus.ORDER_STATUS_TO_BE_PAID.getCode())
                || orderForm.getStatus().equals(
                OrderStatus.ORDER_STATUS_HAVE_PAID.getCode()))) {

            // 支付宝交易状态TRADE_CLOSED，订单状态不是已退款，手动回调
            this.updateRefund(orderForm, queryResponse);
            orderForms.add(t);
        } else if (queryResponse.getTradeStatus().equals(TradeStatus.ALI_WAIT_BUYER_PAY.getCode())) {
            if (orderForm.getStatus().equals(OrderStatus.ORDER_STATUS_HAVE_PAID.getCode())
                    || orderForm.getStatus().equals(OrderStatus.ORDER_STATUS_REFUND.getCode())) {

                // 支付宝交易状态WAIT_BUYER_PAY，订单状态等于已支付或者已退款，更改为待支付
                this.updateNotPay(orderForm.getId());
                orderForms.add(t);
            }
        }
    }

    /**
     * 查询订单校正
     *
     * @param orderForm 订单信息
     * @throws Exception 异常信息
     */
    public void doUpdateBusiness(OrderForm orderForm, List<OrderForm> orderForms) throws Exception {
        if (orderForms == null) {
            orderForms = Lists.newArrayList();
        }
        OrderForm t = orderFormService.get(orderForm.getId());
        Object responseObject = this.orderquery(orderForm.getId());
        if (responseObject != null) {
            if (PaymentWay.WECHAT_PAY.getCode().equals(orderForm.getPaymentWay())) {
                WechatPayQueryResponse response = (WechatPayQueryResponse) responseObject;
                if (Constant.WECHAT_SUCCESS.equals(response.getReturnCode())
                        && Constant.WECHAT_SUCCESS.equals(response.getResultCode())) {
                    this.wxCallback(response, orderForm, orderForms);
                } else {
                    t.setMerchantId(null);
                    t.setTradeState(response.getErrCode());
                    orderFormService.update(t);
                }
            } else if (PaymentWay.ALI_PAY.getCode().equals(orderForm.getPaymentWay())) {
                AliPayQueryResponse response = (AliPayQueryResponse) responseObject;
                if (response.getCode().equals(Constant.ALI_SUCCESS_CODE)) {
                    this.aliCallback(response, orderForm, orderForms);
                } else {
                    t.setTradeState(response.getSubCode());
                    t.setMerchantId(null);
                    orderFormService.update(t);
                }
            }
        }
    }

    /**
     * 导出Excel
     *
     * @param exportOrderForms 订单导出实体
     * @param exportPath       导出路径
     * @throws IOException io异常
     */
    public void exportExcel(List<OrderForm> exportOrderForms, String exportPath) throws IOException {
        String date = DateUtils.formatDate(new Date(), "yyyyMMddHHmmss");
        File file = new File(exportPath);
        if (!file.exists()) {
            file.mkdirs();
        }

        String filename = exportPath + File.separator + date + ".xlsx";
        FileOutputStream outputStream = new FileOutputStream(filename);
        Workbook wb = new XSSFWorkbook();
        Sheet sheet0 = wb.createSheet("校正订单导出");
        appendCell(exportOrderForms, sheet0, wb);

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("isCrowdfund", "0");
        params.put("payment", 0);
        params.put("tradeState", "1");
        Set<String> tradeStatus = new HashSet<String>();
        tradeStatus.add(TradeStatus.WX_ORDERNOTEXIST.getCode());
        tradeStatus.add(TradeStatus.ALI_TRADE_NOT_EXIST.getCode());
        params.put("tradeStatus", tradeStatus);
        List<OrderForm> orderForms = orderFormService.webListPage(new OrderForm(), params, null);

        Sheet sheet1 = wb.createSheet("对账异常订单导出");
        appendCell(orderForms, sheet1, wb);
        wb.write(outputStream);
    }

    /**
     * 拼接单元格
     *
     * @param exportOrderForms 订单导出信息
     * @param sheet            sheet
     * @param wb               工作薄
     */
    public void appendCell(List<OrderForm> exportOrderForms, Sheet sheet, Workbook wb) {
        String[] titles = new String[]{"订单编号", "交易单号", "商户号", "订单名称", "下单者",
                "订单类型", "订单金额", "订单状态", "交易状态", "支付方式", "下单时间"};
        Row titleRow = sheet.createRow(0);
        for (int i = 0; i < titles.length; i++) {
            Cell cell = titleRow.createCell(i);
            cell.setCellValue(titles[i]);
        }

        for (int i = 0; i < exportOrderForms.size(); i++) {
            Row row = sheet.createRow(i + 1);
            OrderForm orderForm = exportOrderForms.get(i);
            Cell c0 = row.createCell(0);
            c0.setCellValue(orderForm.getId());
            Cell c1 = row.createCell(1);
            c1.setCellValue(orderForm.getTransactionId());
            Cell c2 = row.createCell(2);
            c2.setCellValue(orderForm.getMerchantId());
            Cell c3 = row.createCell(3);
            c3.setCellValue(orderForm.getTitle());
            Cell c4 = row.createCell(4);
            c4.setCellValue(orderForm.getMember() != null ? orderForm.getMember().getRealname() : "");
            Cell c5 = row.createCell(5);
            c5.setCellValue(OrderType.getValue(orderForm.getType()));

            CellStyle style1 = wb.createCellStyle();
            DataFormat format = wb.createDataFormat();
            style1.setDataFormat(format.getFormat("0.00"));
            Cell c6 = row.createCell(6);
            c6.setCellValue(orderForm.getPayment());
            c6.setCellStyle(style1);

            Cell c7 = row.createCell(7);
            c7.setCellValue(OrderStatus.getValue(orderForm.getStatus()));
            Cell c8 = row.createCell(8);
            c8.setCellValue(orderForm.getTradeState());
            Cell c9 = row.createCell(9);
            c9.setCellValue(PaymentWay.getValue(orderForm.getPaymentWay()));
            Cell c10 = row.createCell(10);
            c10.setCellValue(DateUtils.formatDate(orderForm.getCreateDate(), "yyyy-MM-dd HH:mm"));
        }
    }

    /**
     * 处理退款
     *
     * @param orderForm
     */
    public void updateRefund(OrderForm orderForm, Object object) {
        if (orderForm.getType().equals(OrderType.ORDER_CROWD_FUND.getCode())) { // 众筹支持
            supportBizService.refund(orderForm.getGoodsId());
        } else if (orderForm.getType().equals(OrderType.ORDER_ACTIVITY.getCode())
                || OrderType.ORDER_COURSE.getCode().equals(orderForm.getType())) { // 活动报名
            MemberAct memberAct = memberActService.findByOrderId(orderForm.getId());
            memberActBizService.verifyFailNoFree2(memberAct.getId(), object);
        }
    }

    /**
     * 处理支付业务
     *
     * @param orderForm  订单信息
     * @param object     业务实体
     * @param paymentWay 支付方式
     * @throws Exception 异常信息
     */
    @Transactional(readOnly = false)
    public void updatePayBusiness(OrderForm orderForm, Object object, Integer paymentWay) throws Exception {
        payOrder(orderForm, object, paymentWay);
    }

    /**
     * 订单支付
     *
     * @param orderForm  订单信息
     * @param object     业务实体
     * @param paymentWay 支付方式
     * @throws OrderException 订单业务异常
     */
    @Transactional
    public void payOrder(OrderForm orderForm, Object object, Integer paymentWay) throws OrderException {

        // 修改订单状态
        orderForm.setIsPay(PaymentState.IS_PAY.getCode());
        orderForm.setPaymentWay(paymentWay);
        orderForm.setStatus(OrderStatus.ORDER_STATUS_HAVE_PAID.getCode());
        orderFormService.update(orderForm);

        // 如果是活动支付成功，设置活动报名状态
        if (OrderType.ORDER_ACTIVITY.getCode().equals(orderForm.getType())
                || OrderType.ORDER_COURSE.getCode().equals(orderForm.getType())) {
            MemberAct dbMemberAct = memberActService.findByOrderId(orderForm.getId());
            if (dbMemberAct != null) {
                dbMemberAct.setCheckStatus(ActStatus.ACT_STATUS_PAID.getCode()); // 已支付，报名成功
                dbMemberAct.setPayStatus(MemberAct.PAY_STATUS_YES);
                memberActService.update(dbMemberAct);
            }
        }

        // 处理众筹主订单
        if (OrderType.ORDER_ACTIVITY.getCode().equals(orderForm.getType())
                && !TradeStatus.ZCXM.getCode().equals(orderForm.getMerchantId())) {
            try {
                memberMerchantDetailBizService.updateOrderNum(orderForm.getInitiatorId(), orderForm.getPayment());
            } catch (Exception e) {
                logger.error("实时更新机构订单统计数异常", e);
            }

            try {
                memberMerchantDetailBizService.updateApplyNum(orderForm.getInitiatorId());
            } catch (Exception e) {
                logger.error("实时更新机构报名统计数异常", e);
            }
        }

        //持久化交易信息
        orderTradeBizService.save(orderForm, object, paymentWay);

        //如果是众筹订单
        //如果是众筹订单
        if (orderForm.getType().equals(OrderType.ORDER_CROWD_FUND.getCode())
                || orderForm.getType().equals(OrderType.ORDER_MULTIPLE_CROWD_FUND.getCode())) {
            this.paySupport(orderForm);
            return;
        }

        // 如果是众筹订单
        if (orderForm.getType().equals(OrderType.ORDER_MALL.getCode())) {
            mallOrderBizService.payMall(orderForm.getId());
            return;
        }

        if (OrderType.ORDER_ACTIVITY.getCode().equals(orderForm.getType())
                || OrderType.ORDER_COURSE.getCode().equals(orderForm.getType())) {
            //只有活动有销售量
            activityService.countSales(orderForm.getGoodsId(), orderForm.getPayment());
        }
    }

    /**
     * 支持订单支付成功回调
     *
     * @param orderForm 订单信息
     */
    @Transactional
    public void paySupport(OrderForm orderForm) {
        //修改支持状态
        Support support = supportService.findByOrderId(orderForm.getId());
        support.setPayStatus(SUPPORT_IS_PAY);
        supportService.update(support);

        //更改众筹
        Project project = projectService.get(support.getProjectId());

        //最后支持时间
        Date now = DateUtils.getTodayDate();
        project.setLastSupportDate(now);
        //支持前百分比
        int beforePercent = this.getPercent(project);

        TargetProject targetProject = targetProjectService.findByProjectId(project.getId());
        int favorerNum = project.getFavorerNum() + 1;
        float actualAmount = supportService.sumByProjectId(project.getId());

        //实时已筹集金额
        project.setRealTimeAmount(actualAmount);
        //已筹金额是否大于目标金额
        actualAmount = actualAmount > project.getTargetAmount() ? project.getTargetAmount() : actualAmount;
        project.setFavorerNum(favorerNum);
        project.setActualAmount(actualAmount);

        //更改项目
        Activity activity = activityService.get(targetProject.getTargetId());

        //如果众筹成功
        boolean isSueccess = projectService.isSuccess(project.getTargetAmount(), project.getActualAmount());
        if ((!project.getIsSuccess().equals(Constant.IS_SUCCESS)) && isSueccess) {
            //修改众筹主订单
            OrderForm mainOrder = orderFormService.get(targetProject.getOrderId());
            this.payOrder(mainOrder, null, PaymentWay.CROWD_FUND_PAY.getCode());
            project.setIsSuccess(Constant.IS_SUCCESS);

            // 商品正在众筹人数减
            activity.setCrowdfundedNum(activity.getCrowdfundedNum() + 1);
            Integer beCrowdfundNum = activity.getBeCrowdfundNum() - 1 <= 0 ? 0 : activity.getBeCrowdfundNum() - 1;
            activity.setBeCrowdfundNum(beCrowdfundNum);

            //更新成功数
            memberCopartnerDetailBizService.updateSuccess(project.getId());

            //更新联合发起统计
            try {
                logger.info("众筹信息", project);
                distributorCountService.countSuccessNum(project.getId());
            } catch (Exception e) {
                logger.error("更新联合发起统计异常", e);
            }
        }
        projectService.update(project);

        //支持后百分比
        int afterPercent = this.getPercent(project);

        int actFavorerNum = activity.getFavorerNum() + 1;
        activity.setFavorerNum(actFavorerNum);
        activityService.update(activity);

        try {
            crowdfundRankService.doCrowdRank(afterPercent, beforePercent, activity, targetProject, support, project);
        } catch (Exception e) {
            logger.error("保存众筹排名异常", e);
        }

        try {
            memberMerchantDetailBizService.updateOrderNum(activity.getMember(), orderForm.getPayment());
        } catch (Exception e) {
            logger.error("实时更新机构订单统计数异常", e);
        }

        try {
            memberCopartnerDetailBizService.updateOrderAnalyze(project.getId(), orderForm.getPayment());
        } catch (Exception e) {
            logger.error("实时更新合伙人订单统计数异常", e);
        }
        //机构用户
        partnerMemberService.insert(activity.getMember(), orderForm.getMemberId());
    }

    public int getPercent(Project project) {
        //支持前百分比
        double percent = BigDecimalUtils.div(project.getActualAmount(), project.getTargetAmount(), 2);
        int intPercent = BigDecimalUtils.amplify2int(percent, 1);
        return intPercent;
    }

    /**
     * 执行查询
     *
     * @param orderId 订单编号
     * @return 查询结果
     * @throws Exception 异常信息
     */
    public Object orderquery(String orderId) throws Exception {
        if (StringUtils.isEmpty(orderId)) {
            logger.error("订单号不能为空");
            return null;
        }
        OrderForm orderForm = orderFormService.get(orderId);
        if (orderForm.getPaymentWay() == null) {
            return null;
        }
        if (orderForm.getPaymentWay().equals(PaymentWay.ALI_PAY.getCode())) {

            // 支付宝
            AliPayRefundInput input = new AliPayRefundInput();
            input.setGateway("https://openapi.alipay.com/gateway.do");
            input.setMethod("alipay.trade.query");
            input.setAppId(appId);
            input.setPrivateKey(privateKey);
            input.setPublickey(publickey);
            input.setSignType(signType);
            return queryAliBizService.getQueryResponse(input, orderId);
        } else if (orderForm.getPaymentWay().equals(PaymentWay.WECHAT_PAY.getCode())) {

            // 微信
            String appId = "";
            String mchId = "";
            String apiKey = "";
            if (orderForm.getTradeType() == null) {
                return null;
            }
            if (orderForm.getTradeType().equals(Constant.CLIENT_WX_WWZ) || orderForm.getTradeType().equals(Constant.CLIENT_WX_PC)) {
                WechatMerchants wechatMerchants = wechatMerchantsService.getSystem();
                WechatOpenMember wechatOpenMember = wechatOpenMemberService.getSystem();
                appId = wechatOpenMember.getAuthorizerAppid();
                mchId = wechatMerchants.getMerchantId();
                apiKey = wechatMerchants.getMerchantApiKey();
            } else if (orderForm.getTradeType().equals(Constant.CLIENT_WX_APP)) {
                appId = app_appId;
                mchId = app_mchId;
                apiKey = app_apiKey;
            } else if (orderForm.getTradeType().equals(Constant.CLIENT_WX_XCX)) {
                appId = xcx_appId;
                mchId = xcx_mchId;
                apiKey = xcx_apiKey;
            }

            WechatPayRefundInput input = new WechatPayRefundInput();
            input.setAppId(appId);
            input.setMchId(mchId);
            input.setApiKey(apiKey);
            input.setRefundUrl("https://api.mch.weixin.qq.com/pay/orderquery");
            return queryWechatBizService.getQueryResponse(input, orderId);
        }
        return null;
    }
}
